<template>
  <view>
    <!-- #ifdef MP-WEIXIN -->
    <uv-navbar
      :fixed="false"
      :title="title"
      left-arrow
      @leftClick="$onClickLeft"
    />
    <!-- #endif -->
    <view class="px-2 mt-2">
      <view class="bg-white p-2">
        <uv-form :model="form" ref="uForm">
          <uv-form-item>
            <view v-if="address.realName">
              <view>{{ address.address }} {{ address.detail }}</view>
              <text>{{ address.realName }} {{ address.phone }}</text>
            </view>
            <view v-else>{{
              currentLanguageTexts.selectRecipientAddress
            }}</view>
            <template #right>
              <uv-icon name="arrow-right" @click="chooseAddress"></uv-icon>
            </template>
          </uv-form-item>
        </uv-form>
      </view>
      <view class="bg-white p-2 mt-2">
        <view class="mb-5">{{ currentLanguageTexts.pointsMall }}</view>
        <view class="flex justify-between">
          <view class="flex">
            <image :src="product.image" mode="aspectFill" class="image"></image>
            <text class="font-size-medium">{{ product.title }}</text>
          </view>
          <view class="flex flex-column">
            <text class="font-size-medium" v-if="isOrigin == 1"
              >{{ product.score }}{{ currentLanguageTexts.points }} +
              {{ product.price }}{{ currentLanguageTexts.yuan }}</text
            >
            <text class="font-size-medium" v-else
              >{{ product.otPrice }}{{ currentLanguageTexts.yuan }}</text
            >
            <text class="font-size-medium text-color-assist mt-2 text-right"
              >×1</text
            >
          </view>
        </view>
        <view class="flex justify-between mt-5" v-if="isOrigin == 1">
          <text class="font-size-medium">{{
            currentLanguageTexts.originalPrice
          }}</text>
          <text class="font-size-medium" style="text-decoration: line-through"
            >{{ product.otPrice }}{{ currentLanguageTexts.yuan }}</text
          >
        </view>
      </view>
    </view>
    <view class="buckle">
      <view class="discount big">
        <text class="title">{{ currentLanguageTexts.platformDiscounts }}</text>
      </view>
      <view class="discount">
        <text class="title">{{ currentLanguageTexts.totalAmountOfGoods }}</text>
        <view class="fares">
          {{ product.otPrice }}{{ currentLanguageTexts.yuan }}
        </view>
      </view>
      <view class="discount">
        <text class="title">{{ currentLanguageTexts.pointsSaved }}</text>
        <view class="fares cut">
          -{{ product.otPrice - product.price }}{{ currentLanguageTexts.yuan }}
        </view>
      </view>
      <view class="discount">
        <text class="title">{{ currentLanguageTexts.logisticsFreight }}</text>
        <view class="fares"> 0元 </view>
      </view>
    </view>
    <view>
      <view class="order">
        <view class="commodity">
          <text class="title">{{ currentLanguageTexts.payWay }}</text>
          <text class="pay-type">{{
            currentLanguageTexts.strictlySelectInsuranceCoverage
          }}</text>
        </view>
        <view v-for="(pay, index) in payOptions" :key="index">
          <view class="method" :key="pay.id" @click="payType = pay.id">
            <image class="method_img" :src="pay.img" mode="widthFix"></image>
            <view class="payment">
              <view class="wx">
                <text class="title">{{ pay.title }}</text>
                <view class="use">
                  使用{{ pay.title }}支付
                  <text class="safety">{{ pay.desc }}</text>
                </view>
              </view>
              <uni-icons
                v-if="payType == pay.id"
                type="circle-filled"
                size="23"
                color="#FF162E"
              ></uni-icons>
              <uni-icons
                v-else
                type="circle"
                size="23"
                color="#ccc"
              ></uni-icons>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="fixed-bottom flex justify-between align-center bg-white">
      <view class="mx-2 ont-weight-light" v-if="isOrigin == 1"
        >{{ currentLanguageTexts.amountTo }}:<text class="text-danger"
          >{{ product.score }}{{ currentLanguageTexts.points }} +
          {{ product.price }}{{ currentLanguageTexts.yuan }}</text
        ></view
      >
      <view class="mx-2 ont-weight-light" v-else
        >{{ currentLanguageTexts.amountTo }}:<text class="text-danger"
          >{{ product.otPrice }}{{ currentLanguageTexts.yuan }}</text
        ></view
      >
      <view
        ><uv-button
          type="warning"
          color="#FF162E"
          :customStyle="customStyle"
          size="large"
          :text="
            isOrigin == 1
              ? currentLanguageTexts.redeemNow
              : currentLanguageTexts.buyNow
          "
          @click="submit"
        ></uv-button
      ></view>
    </view>
    <uv-toast ref="uToast" />
  </view>
</template>

<script setup>
import { ref, computed, getCurrentInstance } from 'vue';
import { onReachBottom, onLoad, onPullDownRefresh } from '@dcloudio/uni-app';
import { scoreShopExchange, scoreShopDetail } from '@/api/score';
import { payUnify } from '@/api/order';
import cookie from '@/utils/cookie';
import { useMainStore } from '@/store/store';
import { storeToRefs } from 'pinia';
const { proxy } = getCurrentInstance();
const main = useMainStore();
const { address, isLogin, currentLanguageTexts } = storeToRefs(main);

const title = ref(currentLanguageTexts.value.confirm);
const product = ref({});
const payOptions = ref([
  {
    id: 1,
    title: currentLanguageTexts.value.WeChat,
    desc: currentLanguageTexts.value.Safeandconvenient,
    img: '',
  },
]);
const payType = ref(1);
const isOrigin = ref(1); //0-原价 1-积分兑换

const customStyle = computed(() => {
  return {
    paddingLeft: '60rpx',
    paddingRight: '60rpx',
  };
});

onLoad(() => {
  if (!isLogin.value) {
    uni.navigateTo({ url: '/pages/components/pages/login/login' });
  }
  product.value = cookie.get('score_product');
  isOrigin.value = cookie.get('is_origin');
});

// 选择地址
const chooseAddress = () => {
  uni.navigateTo({
    url: '/pages/components/pages/address/address?is_choose=true&scene=scoreShop',
  });
};

// 提交
const submit = async () => {
  if (!address.value.id) {
    proxy.$refs.uToast.show({
      message: currentLanguageTexts.value.selectRecipientAddress,
      type: 'warning',
    });
    return;
  }
  let data = await scoreShopExchange({
    productId: product.value.id,
    addressId: address.value.id,
    num: 1,
    isOrigin: isOrigin.value,
    payType: 'weixin',
  });

  if (data == '0') {
    cookie.remove('score_product');
    setTimeout(function () {
      uni.navigateTo({
        url: '/pages/components/pages/scoreproduct/order',
      });
    }, 1000);
  } else {
    weixinPay(data);
  }
};

const weixinPay = async (orderId) => {
  let from = 'routine';
  // #ifdef H5
  from = 'h5';
  if (isWeixin()) {
    from = 'wechat';
  }

  // #endif
  //let that = this;
  let data = await payUnify({
    uni: orderId,
    from: from,
    paytype: 'weixin',
  });

  if (data.trade_type == 'MWEB') {
    // #ifdef H5
    // 微信外的H5
    location.href = data.data;
    // #endif
  } else if (data.trade_type == 'JSAPI') {
    // #ifdef MP-WEIXIN
    uni.requestPayment({
      provider: 'wxpay',
      timeStamp: data.data.timeStamp,
      nonceStr: data.data.nonceStr,
      package: data.data.package,
      signType: 'MD5',
      paySign: data.data.paySign,
      success: function (res) {
        cookie.remove('score_product');
        uni.navigateTo({
          url: '/pages/components/pages/scoreproduct/order',
        });
      },
      fail: function (err) {},
    });
    // #endif
  } else if (data.trade_type == 'W-JSAPI') {
    //公众号支付
    let config = await getWechatConfig();
    if (config) {
      jweixin.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: config.appId, // 必填，公众号的唯一标识
        timestamp: config.timestamp, // 必填，生成签名的时间戳
        nonceStr: config.nonceStr, // 必填，生成签名的随机串
        signature: config.signature, // 必填，签名
        jsApiList: ['chooseWXPay'],
      });
      jweixin.ready(function () {
        jweixin.chooseWXPay({
          timestamp: data.data.timeStamp,
          nonceStr: data.data.nonceStr,
          package: data.data.package,
          signType: 'MD5',
          paySign: data.data.paySign,
          success: function (res) {
            cookie.remove('score_product');
            uni.navigateTo({
              url: '/pages/components/pages/scoreproduct/order',
            });
          },
          fail: function (err) {},
        });
      });
      jweixin.error(function (res) {});
    } else {
    }
  }
};
</script>

<style lang="scss" scoped>
.image {
  width: 160rpx;
  height: 160rpx;
  margin-right: 30rpx;
  border-radius: 8rpx;
}
.buckle {
  margin: 20rpx auto;
  background-color: #fff;
  position: relative;
  border-radius: 10rpx;
  padding: 15rpx 30rpx 30rpx;
  .discount {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-weight: bold;
    margin-bottom: 10rpx;
    padding: 20rpx 0;
    &.big {
      font-size: $font-size-lg;
    }
    .cut {
      color: $theme-color;
    }
  }
}
.order {
  margin: 20rpx auto;
  background-color: #fff;
  position: relative;
  border-radius: 10rpx;
  .commodity {
    width: 95%;
    margin: 0 auto;
    display: flex;
    align-items: center;
    padding-top: 30rpx;
    font-size: $font-size-lg;
    .pay-type {
      background-color: #00b34a;
      padding: 0 10rpx;
      color: #fff;
      border-radius: 30rpx;
      font-size: 11px;
      margin-left: 10rpx;
    }
  }
  .title {
    font-weight: bold;
  }
  .method {
    width: 95%;
    margin: 0 auto;
    display: flex;
    align-items: center;
    .method_img {
      width: 80rpx;
      height: 80rpx;
    }
    .payment {
      margin-left: 30rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex: 1;
      .wx {
        display: flex;
        flex-direction: column;
        justify-content: center;
        border-bottom: 1px solid #f5f5ff;
        padding: 40rpx 0;
        .use {
          font-size: $font-size-sm;
          color: $text-color-grey;
          .safety {
            color: #ff162e;
            margin-left: 5rpx;
          }
        }
      }
    }
  }
}
</style>
